/**
 * 需要拦截请求地址
 * xhr request: POST http://c.eastisred.top/api/dispatchprocess/getDouyinReverseNotify 
 *  */


console.log('content script start');

let pageConfig = {
    voicePath:""
}

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    console.log('接受到参数', request);
    // 修改颜色
    if (request.name == 'changeBg') {
        changBg(request.url, request.opc)
    }
    else if (request.name == 'changeFont') {
        setFontWeight(request.weight)
    }else if (request.name == 'changeVoice') {
        let { path } = request
        pageConfig.voicePath = path
        console.log('当前播放的音色地址',pageConfig.voicePath)
        // setPlayVoice()
    }
});
function changBg(url, opc) {
    console.log('当前需要更改的地址', url);
    let appmain = document.querySelector('.app-main')
    console.log(appmain)
    appmain.style.backgroundImage = `url('${url}')`
    appmain.style.backgroundRepeat = 'no-repeat'
    appmain.style.backgroundSize = 'cover'
    let opcityDom = document.querySelector('.app-main>.w-full')
    opcityDom.style.opacity = opc ? opc : 0.9
}

function setFontWeight(weight) {
    document.querySelector('html').style.fontWeight = weight
}

/**
 * inject injected script
 * 
 * 开始拦截注入
 * 
 * */


/**
 *
 * 抖音订单来了时候处理函数
 *
 * 抖音返回信息格式
 *
 * {
 *     "data": {
 *         "result": [],
 *         "count": 0
 *     },
 *     "success": true,
 *     "code": 0,
 *     "msg": "success",
 *     "timestamp": 1724039906925
 * }
 *
 * */

let audio = null
function createAudio(src){
    audio = new Audio()
    audio.src = chrome.runtime.getURL(src || 'static/source/defaultvoice.WAV')
    audio.addEventListener('canplaythrough', () => {
        // 音频文件已经加载完毕，准备播放
        audio.play().catch(error => {
            console.error('播放音频时出错:', error);
        });
    });
    audio.addEventListener('error', (event) => {
        console.error('音频加载出错:', event);
    });
}

function playAudio(src){
    if(audio){
        audio.src = chrome.runtime.getURL(src || 'static/source/defaultvoice.WAV')
        audio.play()
    }else {
        createAudio(src)
    }
}


function findDouyinOrderHandler(responseData){
    let { data } = responseData
    console.log('data_count----',data.data.count)
    if(data && data.success && data.data.count > 0){
        console.log('Blocked Order 需要播报音乐', '事件名称:',data.eventName,'method:', data.method,'请求地址:', data.url,)
        playAudio()
        return
    }
    playAudio()
}


/**
 * @name dispatchOrderCountHandler
 * @description 拦截分配订单的数量
 *
 * */

function dispatchOrderCountHandler(responseData){
    let { data } = responseData
    console.log('待处理订单数量',data.data,'\n播放订单音乐地址',pageConfig.voicePath || 'static/source/defaultvoice.WAV')
    if(data && data.success && data.data > 0){
        console.log('Blocked Order 需要播报音乐', '事件名称:',data.eventName,'method:', data.method,'请求地址:', data.url,)
        playAudio(pageConfig.voicePath || 'static/source/defaultvoice.WAV')
        return
    }
    // playAudio(pageConfig.voicePath || 'static/source/defaultvoice.WAV')
}

var s = document.createElement('script');
s.src = chrome.runtime.getURL('injected.js');
s.onload = function () {
    this.remove();
};
(document.head || document.documentElement).appendChild(s);

// receive message from injected script
window.addEventListener('message', function (e) {
    console.log('content script received:', e.data);
    let { eventName } = e.data

    switch (eventName) {
        case 'findDouyinOrder':
            findDouyinOrderHandler(e.data)
            break;
        case 'dispatchOrderCount':
            dispatchOrderCountHandler(e.data)
    }
});